package com.example.diancai.controller;

import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult;
import cn.hutool.core.util.URLUtil;
import com.example.diancai.annotations.IgnoreAuth;
import com.example.diancai.consts.RedisKeyConst;
import com.example.diancai.dto.CurrentPlayer;
import com.example.diancai.dto.request.UpdateUserInfo;
import com.example.diancai.entity.DcUser;
import com.example.diancai.entity.WxUser;
import com.example.diancai.enums.Game2048LevelEnum;
import com.example.diancai.oss.FileService;
import com.example.diancai.service.DcUserService;
import com.example.diancai.service.WxUserService;
import com.example.diancai.util.AuthUtil;
import com.example.diancai.util.RedisUtil;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.stereotype.Controller;

import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.time.LocalDateTime;
import java.util.UUID;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author q
 * @since 2025-03-07
 */
@Controller
@RequestMapping("/user")
public class DcUserController {
    @Autowired
    private WxMaService wxMaService;
    @Autowired
    private DcUserService dcUserService;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private FileService fileService;
    // 微信小程序登录接口
    @GetMapping("/wxLogin/{code}")
    @IgnoreAuth
    public String login(@PathVariable String code) throws WxErrorException {


        WxMaJscode2SessionResult sessionInfo =
                wxMaService.getUserService().getSessionInfo(code);

        // 已经有token了，还用之前的token
        if (redisUtil.hasKey(RedisKeyConst.AUTH + sessionInfo.getOpenid())) {
            return redisUtil.getObj(RedisKeyConst.AUTH + sessionInfo.getOpenid(), String.class);
        }

        DcUser dcUser = dcUserService.getById(sessionInfo.getOpenid());

        String token = UUID.randomUUID().toString();
        CurrentPlayer currentPlayer = new CurrentPlayer();
        BeanUtils.copyProperties(dcUser, currentPlayer);
        currentPlayer.setSession(sessionInfo);
        redisUtil.setObject(RedisKeyConst.AUTH + token, currentPlayer);
        redisUtil.setObject(RedisKeyConst.AUTH + currentPlayer.getWxId(), token);
        return token;
    }

    @GetMapping("/me")
    public CurrentPlayer getCurrentUser() {
        return AuthUtil.getCurrPlayer();
    }

    @PostMapping("/updateUser")
    public void updateUser(@RequestBody UpdateUserInfo updateUserInfo) throws MalformedURLException {

        DcUser  dcUser = dcUserService.getById(AuthUtil.getCurrPlayerId());
        dcUser.setDcName(updateUserInfo.getNickName());
        // 头像
        String headUrl = updateUserInfo.getHeadUrl();
        InputStream stream = URLUtil.getStream(new URL(headUrl));
        String url = fileService.uploadOss("userHeader" + dcUser.getuId() + ".png", stream);
        dcUser.setPictureUrl(url);
        CurrentPlayer currPlayer = AuthUtil.getCurrPlayer();
        currPlayer.setWxHead(url);
        currPlayer.setWxUsername(updateUserInfo.getNickName());

        redisUtil.setObject(RedisKeyConst.AUTH + AuthUtil.getToken(), currPlayer);

        dcUserService.updateById(dcUser);
    }
    @PostMapping("/addUser")
    public void addUser(@RequestBody UpdateUserInfo updateUserInfo) throws MalformedURLException {
        DcUser dcUser = new DcUser();
        BeanUtils.copyProperties(updateUserInfo, dcUser);
        dcUser.setuId(UUID.randomUUID().toString());
        // 头像
        String headUrl = updateUserInfo.getHeadUrl();
        InputStream stream = URLUtil.getStream(new URL(headUrl));
        String url = fileService.uploadOss("userHeader" + dcUser.getuId() + ".png", stream);

        dcUser.setPictureUrl(url);
        CurrentPlayer currPlayer = AuthUtil.getCurrPlayer();
        currPlayer.setWxHead(url);
        currPlayer.setWxUsername(updateUserInfo.getNickName());

        redisUtil.setObject(RedisKeyConst.AUTH + AuthUtil.getToken(), currPlayer);

        dcUserService.save(dcUser);
    }

    @GetMapping("/tokenEffective")
    @IgnoreAuth
    public boolean tokenEffective(@RequestParam String token) {
        return redisUtil.hasKey(RedisKeyConst.AUTH + token);
    }

}
